package com.tang.client;

import com.tang.domain.MsgInfo;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

/**
 * nettyClient启动类
 *
 * @author fulin.tang
 * @version V3.0
 * @since 2021/9/13 12:00
 */
@Slf4j
public class NettyClient {

    public static void main(String[] args) {
        new NettyClient().connect();
    }

    private void connect() {
        EventLoopGroup workGroup = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(workGroup);
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.option(ChannelOption.AUTO_READ, true);
            bootstrap.handler(new MyChannelInitializer());
            ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 7397).sync();
            log.info("客户端启动成功啦!");
            String channelId = channelFuture.channel().id().toString();
            
            channelFuture.channel().writeAndFlush( MsgInfo.builder().channelId(channelId).msgContent("这是起始的消息啦啦啦!").build());
            channelFuture.channel().writeAndFlush( MsgInfo.builder().channelId(channelId).msgContent("小汤汤快点好起来!").build());
            channelFuture.channel().writeAndFlush( MsgInfo.builder().channelId(channelId).msgContent("老汤一定要健康!").build());
            channelFuture.channel().writeAndFlush( MsgInfo.builder().channelId(channelId).msgContent("小市民就是一家人健健康康就够了!").build());
            channelFuture.channel().writeAndFlush( MsgInfo.builder().channelId(channelId).msgContent("加油努力学习挣小钱钱!").build());
            
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            workGroup.shutdownGracefully();
        }
    }
    
}
